package com.mayikt.pay.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mayikt.core.util.GenerateTokenUtils;
import com.mayikt.pay.mapper.entity.PaymentTransaction;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.pay.mapper.PaymentTransactionMapper;
import com.mayikt.pay.service.PayMentTransacInfoService;
import com.mayikt.weixin.out.dto.PayMentTransacDTO;

@RestController
@Service
@Slf4j
public class PayMentTransacInfoServiceImpl extends BaseApiService<PayMentTransacDTO> implements PayMentTransacInfoService {
	@Autowired
	private GenerateTokenUtils generateToken;
	@Autowired
	private PaymentTransactionMapper paymentTransactionMapper;

	@Override
	public BaseResponse<PayMentTransacDTO> tokenByPayMentTransac(String token) {
		// 1.验证token是否为空
		if (StringUtils.isEmpty(token)) {
			return setResultError("token参数不能空!");
		}
		// 2.使用token查询redisPayMentTransacID
		String value = generateToken.getToken(token);
		if (StringUtils.isEmpty(value)) {
			return setResultError("该Token可能已经失效或者已经过期");
		}
		// 3.转换为整数类型
		Long transactionId = Long.parseLong(value);
		// 4.使用transactionId查询支付信息
		PaymentTransaction paymentTransaction = paymentTransactionMapper.selectById(transactionId);
		if (paymentTransaction == null) {
			return setResultError("未查询到该支付信息");
		}
		PayMentTransacDTO payMentTransacDTO = new PayMentTransacDTO();
		BeanUtils.copyProperties(paymentTransaction,payMentTransacDTO);
		return setResultSuccess(payMentTransacDTO);
	}

    /**
     * /**通过paymentId 改变订单状态
     * @param orderId
     * @param status
     * @return
     */
    @Override
    public int updateStaByorderId(String orderId, int status) {
        return paymentTransactionMapper.updateStaByorderId(orderId,status);
    }


	/**
	 * 通过orderId查询paymentTransaction 订单信息
	 * @param orderId
	 * @return
	 */
	public PaymentTransaction selByOrderId(String orderId){
		if (StrUtil.isEmpty(orderId)){
			log.info("orderId 为空");
			return null;
		}
		QueryWrapper<PaymentTransaction> queryWrapper = new QueryWrapper();
		queryWrapper.lambda().eq(PaymentTransaction::getOrderId,orderId);
		return paymentTransactionMapper.selectOne(queryWrapper);
	}
}
